package com.lwc.backendsinglestructure.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.lwc.backendsinglestructure.domain.vo.wx.ReceiveMessage;
import org.thymeleaf.util.StringUtils;

import java.util.HashMap;

/**
 * @author https://www.wdbyte.com
 */
public class WeixinMsgUtil {

    // 事件-关注
    private static String EVENT_SUBSCRIBE = "subscribe";

    /**
     * 微信消息转对象
     *
     * @param xml
     * @return
     */
    public static ReceiveMessage msgToReceiveMessage(String xml) {
        JSONObject jsonObject = JSONUtil.parseFromXml(xml);
        HashMap<String,Object> hashMap = jsonObject.get("xml", HashMap.class);
        ReceiveMessage receiveMessage = new ReceiveMessage();
        receiveMessage.setToUserName((String) hashMap.get("ToUserName"));
        receiveMessage.setFromUserName((String) hashMap.get("FromUserName"));
        receiveMessage.setCreateTime((Integer) hashMap.get("CreateTime"));
        receiveMessage.setMsgType((String) hashMap.get("MsgType"));
        receiveMessage.setContent((String) hashMap.get("Content"));
        receiveMessage.setMsgId((String) hashMap.get("MsgId"));
        receiveMessage.setEvent((String) hashMap.get("Event"));
        receiveMessage.setTicket((String) hashMap.get("Ticket"));
        return receiveMessage;
    }

    /**
     * 是否是订阅事件
     *
     * @param receiveMessage
     * @return
     */
    public static boolean isEventAndSubscribe(ReceiveMessage receiveMessage) {
        return StringUtils.equals(receiveMessage.getEvent(), EVENT_SUBSCRIBE);
    }

    /**
     * 是否是二维码扫描事件
     *
     * @param receiveMessage
     * @return
     */
    public static boolean isScanQrCode(ReceiveMessage receiveMessage) {
        return StrUtil.isNotEmpty(receiveMessage.getTicket());
    }

    /**
     * 获取扫描的二维码 Ticket
     *
     * @param receiveMessage
     * @return
     */
    public static String getQrCodeTicket(ReceiveMessage receiveMessage) {
        return receiveMessage.getTicket();
    }

}